package com.example.mingyue.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mingyue.constant.MqConstant;
import com.example.mingyue.datasource.DataSource;
import com.example.mingyue.model.dto.PostDto;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.model.entity.User;
import com.example.mingyue.service.PostService;
import com.example.mingyue.mapper.PostMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
* @author 我自飞扬临天下
* @description 针对表【post(帖子)】的数据库操作Service实现
* @createDate 2025-01-10 11:37:01
*/
@Service
@Slf4j
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
    implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增帖子
     * @param postDto
     */
    @Override
    public void addPost(PostDto postDto) {
        Post post = new Post();
        BeanUtils.copyProperties(postDto,post);

        postMapper.insert(post);

        rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_INSERTPOST_KEY,post.getId());
    }

    /**
     * 删除帖子
     * @param id
     */
    @Override
    public void deletePost(Integer id) {
        postMapper.deleteById(id);
        rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_DELETEPOST_KEY,id);
    }

    @Autowired
    private RestHighLevelClient client;

    /**
     * 同步ES 新增帖子
     * @param id
     */
    @Override
    public void insertPostES(Integer id) {
        Post post = postMapper.selectById(id);

        try {
            IndexRequest request = new IndexRequest("post").id(post.getId().toString());
            request.source(JSON.toJSONString(post), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步ES删除帖子
     * @param id
     */
    @Override
    public void deletePostES(Integer id) {
        try {
            DeleteRequest request = new DeleteRequest("post",id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }



}




